<template>
  <div class="app-container">
    <el-form
      :inline="true"
      v-loading="loading"
      class="form-container"
      ref="form"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="文章标题" prop="articleTitle">
            <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4}"
              v-model="form.articleTitle"
              clearable
              placeholder="请输入文章标题"
              :style="{ width: '300px'}"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="文章分类" prop="categoryId">
            <el-select filterable clearable v-model="form.categoryId">
              <el-option
                v-for="item in categoryOptions"
                :key="item.categoryId"
                :label="item.categoryName"
                :value="item.categoryId"
                :disabled="item.status == 1"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="文章标签" prop="articleTags">
            <el-select filterable clearable multiple v-model="form.articleTags">
              <el-option
                v-for="item in tagOptions"
                :key="item.tagId"
                :label="item.tagName"
                :value="item.tagId"
                :disabled="item.status == 1"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="文章类型" prop="articleType">
            <el-radio-group v-model="form.articleType">
              <el-radio-button
                v-for="dict in dict.type.blog_article_type"
                :key="dict.value"
                :label="dict.value"
              >{{ dict.label }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            v-if="form.articleType !== '0'"
            label="原文链接"
            prop="originalUrl"
          >
            <el-input v-model="form.originalUrl" placeholder="请输入内容"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="文章状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio-button
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.value"
              >{{ dict.label }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否置顶" prop="isTop">
            <el-radio-group v-model="form.isTop">
              <el-radio-button
                v-for="dict in dict.type.blog_is_top"
                :key="dict.value"
                :label="dict.value"
              >{{ dict.label }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="文章图片" prop="articleImage">
            <image-upload :limit="1" :file-size="1" v-model="form.articleImage"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="文章内容" prop="articleContent">
            <div style="width: 1200px;">
              <mavon-editor ref="md" v-model="form.articleContent" @imgAdd="handleEditorImgUpload"/>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="form-footer">
      <el-button type="primary" :loading="buttonLoading" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import {
  addArticle,
  getArticle,
  updateArticle
} from '@/api/blog/article'
import {
  upload
} from '@/api/system/oss'
import { queryCategoryList } from '@/api/blog/category'
import { queryTagList } from '@/api/blog/tag'
import store from '@/store'
import router from '@/router'
import MiddleUtil from '@/utils/middleUtil'

export default {
  name: 'ArticleOperate',
  dicts: ['sys_normal_disable', 'blog_article_type', 'blog_is_top'],
  data() {
    return {
      buttonLoading: false,
      categoryOptions: [],
      tagOptions: [],
      // 遮罩层
      loading: false,
      // 表单参数
      form: {},
      rules: {
        categoryId: [
          { required: true, message: '文章分类不能为空', trigger: 'blur' }
        ],
        articleTitle: [
          { required: true, message: '文章标题不能为空', trigger: 'blur' }
        ],
        articleContent: [
          { required: true, message: '文章内容不能为空', trigger: 'blur' }
        ],
        articleImage: [
          { required: true, message: '文章图片不能为空', trigger: 'blur' }
        ],
        articleType: [
          { required: true, message: '文章类型不能为空', trigger: 'change' }
        ],
        originalUrl: [
          { required: true, message: '原文链接不能为空', trigger: 'blur' }
        ],
        isTop: [
          { required: true, message: '是否置顶不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '状态不能为空', trigger: 'change' }
        ],
        articleTags: [
          { required: true, message: '文章标签不能为空', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll);
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll)
  },
  created() {
    this.reset()
    this.getCategoryList()
    this.getTagList()
    this.form.articleId = this.$route.params && this.$route.params.articleId
    if (this.form.articleId) {
      this.loading = true
      getArticle(this.form.articleId).then((res) => {
        this.form = res.data
        this.loading = false
      })
    }
  },
  methods: {
    //当文章内容过多时，不方便操作工具栏，因此让工具栏随着页面滚动
    handleScroll() {
      const mdToolbar = document.querySelector('.v-note-op'); // 工具栏元素
      const toolbarHeight = mdToolbar.offsetHeight*12; // 工具栏高度
      console.log("窗口高度："+window.pageYOffset)
      console.log("工具栏："+toolbarHeight)
      if (window.scrollY >= toolbarHeight) {
        mdToolbar.style.position = 'fixed';
        mdToolbar.style.top = '0';
        mdToolbar.style.width = '1200px';
      } else {
        // 移除样式
        mdToolbar.style.position = '';
        mdToolbar.style.top = '';
        mdToolbar.style.width = '';
      }
    },
    handleEditorImgUpload(pos, file) {
      if (file.type.indexOf('image/') == -1) {
        this.$modal.msgError('文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。')
      }
      let formData = new FormData()
      formData.append('file', file)
      upload(formData).then(res => {
        this.$refs.md.$img2Url(pos, res.data.url)
        this.$modal.msgSuccess('上传成功')
      })
    },
    getCategoryList() {
      queryCategoryList().then((res) => {
        this.categoryOptions = res.data
      })
    },
    getTagList() {
      queryTagList().then((res) => {
        this.tagOptions = res.data
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.buttonLoading = true
          if (this.form.articleId != undefined) {
            updateArticle(this.form)
              .then((response) => {
                this.$modal.msgSuccess('修改成功')
                this.backAndResetForm()
              })
              .finally(() => {
                this.buttonLoading = false
              })
          } else {
            addArticle(this.form)
              .then((response) => {
                this.$modal.msgSuccess('新增成功')
                this.backAndResetForm()
              })
              .finally(() => {
                this.buttonLoading = false
              })
          }
        }
      })
    },
    // 取消按钮
    cancel() {
      this.backAndResetForm()
    },
    //返回并重置表单
    backAndResetForm() {
      this.reset()
      MiddleUtil.$emit('getList');
      store.dispatch('tagsView/delView', router.currentRoute)
      this.$router.replace('/blog/article')
    },
    // 表单重置
    reset() {
      this.form = {
        articleId: undefined,
        categoryId: undefined,
        articleTitle: undefined,
        articleContent: undefined,
        articleImage: undefined,
        articleType: '0',
        originalUrl: undefined,
        isTop: '0',
        status: '0',
        articleTags: []
      }
      this.resetForm('form')
    }
  }
}
</script>
<style scoped>
.app-container {
  position: relative;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.form-container {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 30px;
  height: calc(100vh - 120px);
}

.form-footer button:first-child {
  margin-right: 10px;
}
</style>
